package com.lry.util.requestcore.handler.parse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lry.util.requestcore.handler.StringParser;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;

/**
 * json解析器
 *
 * @author ALI
 * @since 2023/5/8
 */
public class JsonParser extends StringParser {

    @Override
    public JSONObject parserObj(String data) {
        data = check(data);
        checkObj(data);
        if (!data.startsWith("{") || !data.endsWith("}")) {
            throw new RuntimeException("不规范的json字符串");
        }
        try {
            return JSONObject.parseObject(data);
        } catch (Exception e) {
            throw new RuntimeException("json字符串异常", e);
        }
    }

    public List<Map<String, Object>> parseList(String data) {
        data = check(data);
        if (data.startsWith("{")) {
            return Collections.singletonList(parserObj(data));
        }
        if (!data.startsWith("[") || !data.endsWith("]")) {
            throw new RuntimeException("不规范的json字符串");
        }
        try {
            JSONArray arrays = JSONArray.parseArray(data);
            List<Map<String, Object>> result = new ArrayList<>();
            arrays.forEach(d -> result.add((Map<String, Object>) d));
            return result;
        } catch (Exception e) {
            throw new RuntimeException("json字符串异常", e);
        }
    }

    private void checkObj(String data) {
        if (!data.startsWith("{") || !data.endsWith("}")) {
            throw new RuntimeException("不规范的json字符串");
        }
    }

    private String check(String data) {
        data = data.trim();
        data = StringUtils.removeStart(data, "(");
        data = StringUtils.removeEnd(data, ")");
        data = data.trim();
        return data;
    }

}
